<template>
  <NodeViewWrapper>
    <div
      class="scene-header"
      :id="id"
      :style="{
        padding: '8px 12px',
        margin: '12px 0',
        fontWeight: 'bold',
        fontSize: '18px',
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
        flexWrap: 'wrap',
      }"
    >
      <template v-if="editing">
        <label>
          <span>集</span>
          <input
            ref="jiRef"
            v-model="episode"
            @keydown.enter.prevent="confirmEdit"
            @keydown.esc.prevent="cancelEdit"
            @click.stop
            style="width: 60px; margin-left: 4px;"
            required
          />
        </label>

        <label>
          <span>场</span>
          <input
            ref="changRef"
            v-model="scene"
            @keydown.enter.prevent="confirmEdit"
            @keydown.esc.prevent="cancelEdit"
            @click.stop
            style="width: 60px; margin-left: 4px;"
            required
          />
        </label>
        <input
          v-model="sceneName"
          @keydown.enter.prevent="confirmEdit"
          @keydown.esc.prevent="cancelEdit"
          @click.stop
          style="width: 60px; margin-left: 4px;"
          required
        />

        <select v-model="mood" @click.stop>
            <option value="室内">室内</option>
            <option value="室外">室外</option>
          </select>

          <select v-model="interiorExteriorScene" @click.stop>
            <option value="白天">白天</option>
            <option value="夜晚">夜晚</option>
          </select>

        <button @click="confirmEdit">✅</button>
        <button @click="deleteNode">❌</button>
      </template>

      <span
        v-else
        @click="editNode"
        style="cursor: pointer; user-select: none; flex: 1;"
      >
        {{ episode }}集 {{ scene }}场 ｜ {{ sceneName }} {{ mood }} ｜ {{ interiorExteriorScene }}
      </span>
    </div>
  </NodeViewWrapper>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { NodeViewWrapper } from '@tiptap/vue-3'

const props = defineProps({
  node: Object,
  updateAttributes: Function,
  deleteNode: Function,
  editor: Object,
  getPos: Function,
})

const editing = ref(props.node.attrs.editing ?? true)

// 字段初始化
const id = ref(props.node.attrs.id || '')
const episode = ref(props.node.attrs.episode || '')
const scene = ref(props.node.attrs.scene || '')
const sceneName = ref(props.node.attrs.sceneName || '')
const mood = ref(props.node.attrs.mood || '室内')
const interiorExteriorScene = ref(props.node.attrs.interiorExteriorScene || '白天')
const isNew = ref(true)

const jiRef = ref(null)
const changRef = ref(null)

watch(
  () => props.node.attrs,
  (newVal) => {
    id.value = newVal.id || ''
    episode.value = newVal.episode || ''
    scene.value = newVal.scene || ''
    sceneName.value = newVal.sceneName || ''
    mood.value = newVal.mood || '室内'
    interiorExteriorScene.value = newVal.interiorExteriorScene || '白天'
    editing.value = !!newVal.editing  // ✅ 严格同步 editing 状态
    isNew.value = !!newVal.isNew
  },
  { immediate: true, deep: true }
)

function confirmEdit() {
  if (!episode.value.trim() || !scene.value.trim()) {
    alert('“集”和“场”是必填项')
    return
  }

  props.updateAttributes({
    id: id.value,
    episode: episode.value.trim(),
    scene: scene.value.trim(),
    sceneName: sceneName.value.trim(),
    mood: mood.value,
    interiorExteriorScene: interiorExteriorScene.value,
    editing: false,
    isNew: false,
  })

  editing.value = false
  
  nextTick(() => {
    props.editor?.commands?.focus()
    setTimeout(() => {
      // ✅ 主动触发分页逻辑
      if (typeof window.syncContent === 'function') {
        window.syncContent()
      }
    }, 0)
  })
}

function cancelEdit() {
  editing.value = false
  props.updateAttributes({ editing: false })
}

function editNode() {
  editing.value = true
  props.updateAttributes({ editing: true })
}

function deleteNode() {
  const localPos = props.getPos?.()
  if (typeof localPos !== 'number') return

  const globalPos = window.computeGlobalPos(localPos, props.editor)
  if (isNew.value) {
    // ⛔ 尚未确认的场头，只删除自身节点
    const { state, dispatch } = props.editor.view
    const { tr } = state
    tr.delete(localPos, localPos + props.node.nodeSize)
    dispatch(tr)

    setTimeout(() => {
      window.syncContent?.()
    }, 0)
  } else {
    // ✅ 确认后的场头，连带后续内容一并删除
    window.deleteSceneHeaderGlobal(globalPos)

    setTimeout(() => {
      window.syncContent?.()
    }, 0)
  }
}
</script>
